﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xml;

namespace Zero.UControl.Base.Helper
{
    public static class XamlHelper
    {
        public static void SaveCanvasElementsToFile(Canvas canvas, string filePath, bool clearAfterSave = false)
        {
            try
            {
                using var writer = XmlWriter.Create(filePath, new XmlWriterSettings { Indent = true });
                XamlWriter.Save(canvas, writer);

                if (clearAfterSave)
                    canvas.Children.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public static void LoadCanvasElementsFromFile(Canvas targetCanvas, string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("未找到指定的 XAML 文件", filePath);

            try
            {
                using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (XamlReader.Load(fs) is not Canvas loadedCanvas)
                    throw new InvalidDataException("文件内容不是有效的 Canvas XAML。");
                ReplaceCanvas(targetCanvas, loadedCanvas);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private static void ReplaceCanvas(Canvas oldCanvas, Canvas newCanvas)
        {
            if (VisualTreeHelper.GetParent(oldCanvas) is Panel parent)
            {
                int index = parent.Children.IndexOf(oldCanvas);
                parent.Children.RemoveAt(index);
                parent.Children.Insert(index, newCanvas);
            }
        }
    }
}
